package four;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author      : yang.xp
 * @date        : 2021/12/14 16:45
 * @description : CountDownLatch
 */
public class CountDownLatchTest1 {
	public static void main(String[] args) {
		final CountDownLatch latch = new CountDownLatch(3);
		System.out.println("主线程开始执行 ----- ");

		ExecutorService es1 = Executors.newSingleThreadExecutor();
		es1.execute(() -> {
			try {
				Thread.sleep(3000);
				System.out.println(" 线程 " + Thread.currentThread().getName());
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			latch.countDown();
			System.out.println(" 线程 " + Thread.currentThread().getName() + " 结束 ");
		});

		es1.shutdown();

		ExecutorService es2 = Executors.newSingleThreadExecutor();
		es2.execute(() -> {
			try {
				Thread.sleep(2000);
				System.out.println(" 线程 " + Thread.currentThread().getName());
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			latch.countDown();
			System.out.println(" 线程 " + Thread.currentThread().getName() + " 结束 ");
		});

		es2.shutdown();

		ExecutorService es3 = Executors.newSingleThreadExecutor();
		es3.execute(() -> {
			try {
				Thread.sleep(1000);
				System.out.println(" 线程 " + Thread.currentThread().getName());
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			latch.countDown();
			System.out.println(" 线程 " + Thread.currentThread().getName() + " 结束 ");
		});
		es3.shutdown();
		System.out.println("等待线程执行完毕============  ");
		try {
			latch.await();
			System.out.println("三个线程执行完毕============  ");
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("主线程执行结束==============   ");
	}
}
